/*
 * Copyright (c) 2017. Visionet and/or its affiliates. All right reserved.
 * VISIONET PROPRIETARY/CONFIDENTIAL.
 */
package com.visionet.jumper.core.support.validate;

import com.visionet.jumper.core.common.Message;
import com.visionet.jumper.core.support.spring.SpringMessageUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.validation.constraints.NotNull;

/**
 * @author TC.Ubuntu
 * @since 2017/7/4.
 */
public class JSRValidationAdvice {

	private Logger logger = LoggerFactory.getLogger(JSRValidationAdvice.class);

	/**
	 * 判断验证错误代码是否属于字段为空的情况
	 *
	 * @param code
	 *            验证错误代码
	 */
	private boolean isMissingParamsError(String code) {
		if (code.equals(NotNull.class.getSimpleName())
				|| code.equals(NotBlank.class.getSimpleName())
				|| code.equals(NotEmpty.class.getSimpleName())) {
			return true;
		} else {
			return false;
		}
	}

	public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
		Message msg = new Message();
		BindingResult result = null;
		Object[] args = joinPoint.getArgs();
		if (args != null && args.length != 0) {
			for (Object object : args) {
				if (object instanceof BindingResult) {
					result = (BindingResult) object;
					break;
				}
			}
		}
		if (result != null && result.hasErrors()) {
			FieldError fieldError = result.getFieldError();
			String targetName = joinPoint.getTarget().getClass().getSimpleName();
			String method = joinPoint.getSignature().getName();
			String message = SpringMessageUtils.message(fieldError.getDefaultMessage());
			logger.info("验证失败.控制器:{}, 方法:{}, 参数:{}, 属性:{}, 错误:{}, 消息:{}", targetName, method,
					fieldError.getObjectName(), fieldError.getField(), fieldError.getCode(),
					message);
			String firstCode = fieldError.getCode();
//			if (isMissingParamsError(firstCode)) {
//				msg.setCode("fail");
//				msg.setMsg("必选参数丢失");
//				return msg;
//			} else {
				msg.setCode("fail");
				msg.setMsg(message);
				return msg;
//			}
		}
		return joinPoint.proceed();
	}
}
